package com.yy.common.commonutils;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;
/**
 * 文件下载器
 * Created by Ellis.Li on 2017/7/10.
 */

public class DownFileUtil {
    String TAG  = "XUtilsDownFileUtil";
    private static DownFileUtil instance;
    static HttpUtils httpUtils = null;
    HttpHandler handler = null;
    public static DownFileUtil getInstance(){
        if (instance == null){
            synchronized (DownFileUtil.class){
                instance = new DownFileUtil();
                initHttpUtils();
            }
        }
        return instance;
    }
    public interface FileDownInterface {
        public void start();
        public void onLoading(long total, long current, boolean isUploading);
        public void onSuccess(File file);
        public void onFailure(String errorStr);
    }
    private static void initHttpUtils(){
         httpUtils = new HttpUtils();
    }

    /**
     * 下载文件
     * @param fileUrl
     * @param fileToPath
     * @param fileDownInterface
     */
    public void downFile(String fileUrl, String fileToPath, final FileDownInterface fileDownInterface){
        handler = httpUtils.download(fileUrl,
                fileToPath,
                true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        LogUtils.loge("onStart");
                        fileDownInterface.start();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        LogUtils.loge("onLoading total "+total+"current"+current+"isUploading"+isUploading);
                        fileDownInterface.onLoading(total, current, isUploading);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        LogUtils.loge("onSuccess "+responseInfo.result.getAbsolutePath());
                        fileDownInterface.onSuccess(responseInfo.result);
                        cancelFileDown();
                    }


                    @Override
                    public void onFailure(HttpException error, String msg) {
                        LogUtils.loge("onFailure "+msg);
                        fileDownInterface.onFailure(msg);
                        cancelFileDown();
                    }
                });
    }
    public void cancelFileDown(){
        if (handler != null){
            handler.cancel();
        }
    }
}
